<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use app\educational\model\MessageModel;
use think\Db;
use think\Validate;
use cmf\controller\HomeBaseController;
use app\user\model\UserModel;

class LoginController extends HomeBaseController
{

    /**
     * 登录
     */
    public function index()
    {
        $redirect = $this->request->post("redirect");
        if (empty($redirect)) {
            $redirect = $this->request->server('HTTP_REFERER');
        } else {
            $redirect = base64_decode($redirect);
        }
        session('login_http_referer', $redirect);
        if (cmf_is_user_login()) { //已经登录时直接跳到首页
            return redirect($this->request->root() . '/');
        } else {
            return $this->fetch(":login");
        }
    }

    /**
     * 登录验证提交
     */
    public function doLogin()
    {
        if ($this->request->isPost()) {
            $validate = new Validate([
                'username' => 'require',
                'password' => 'require|min:6|max:32',
                'captcha'  => 'require',
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
                'password.max'     => '密码不能超过32个字符',
                'password.min'     => '密码不能小于6个字符',
                'captcha.require'  => '验证码不能为空',
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            if (!cmf_captcha_check($data['captcha'])) {
                $this->error('验证码错误');
            }

            $userModel         = new UserModel();
            $user['user_pass'] = $data['password'];
            if (Validate::is($data['username'], 'email')) {
                $user['user_email'] = $data['username'];
                $log                = $userModel->doEmail($user);
            } else if (preg_match('/(^(13\d|14[57]|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', $data['username'])) {
                $user['mobile'] = $data['username'];
                $log            = $userModel->doMobile($user);
            } else {
                $user['user_login'] = $data['username'];
                $log                = $userModel->doName($user);
            }
            $session_login_http_referer = session('login_http_referer');
            $redirect                   = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            switch ($log) {
                case 0:
                    //(Steven):多店铺设置
                    $cur_user = session('user');
                    $shop_id = $cur_user["shop_id"] ? $cur_user["shop_id"] : 1;
                    session('FRONT_SHOP_ID', $shop_id);

                    //7月份后孩子上六年级发信息提示更改初中学校全称
                    if(date('n') >= 7){
                        $student = Db::name('student')
                            ->where('u_id','eq',$cur_user['id'])
                            ->where('grade','egt',5)
                            ->select();
                        if(!$student->isEmpty()){
                            $student = $student->toArray();
                            $names = array_column($student,'name');
                            $names = trim(implode(',',$names),',');
                            $content = lang('GRADE_MSG',['name'=>$names]);

                            //查看是否已发过站内信
                            $msg = Db::name('message')->alias('m')
                                ->where('m.shop_id','eq',session('FRONT_SHOP_ID'))
                                ->where('m.delete_time','eq',0)
                                ->where('m.type','eq',0)
                                ->where('m.content','like',"%$content%")
                                ->find();
                            if(count($msg) > 0){
                                //查看是否已给该用户发过信息
                                $msg_user = Db::name('message_user')
                                    ->where('msg_id','eq',$msg['id'])
                                    ->where('receive_uid','eq',$cur_user['id'])
                                    ->find();
                                if(count($msg_user) <= 0){
                                    //发送消息
                                    $umsg_data = [
                                        'msg_id' => $msg['id'],
                                        'receive_uid' => $cur_user['id'],
                                        'msg_status' => 0,
                                    ];
                                    Db::name('message_user')->insert($umsg_data);
                                }

                            }else{
                                //发送消息
                                $msg_data = [
                                    'shop_id' => session('FRONT_SHOP_ID'),
                                    'type' => 0,//站内信
                                    'send_uid' => 1,//管理员
                                    'subject' => '完善学生信息',
                                    'content' => $content,
                                    'create_time' => time(),
                                ];
                                $ids[] = ['id' => $cur_user['id']];

                                $msg_mdl = new MessageModel();
                                $msg_mdl->sendMsg($msg_data, $ids);
                            }
                        }
                    }

                    $this->success('登录成功', $redirect);
                    break;
                case 1:
                    $this->error('登录密码错误');
                    break;
                case 2:
                    $this->error('账户不存在');
                    break;
                default :
                    $this->error('未受理的请求');
            }
        } else {
            $this->error("请求错误");
        }
    }

    /**
     * 找回密码
     */
    public function findPassword()
    {
        return $this->fetch('/find_password');
    }

    /**
     * 用户密码重置
     */
    public function passwordReset()
    {

        if ($this->request->isPost()) {
            $validate = new Validate([
                'username'          => 'require',
                'verification_code' => 'require',
                'password'          => 'require|min:6|max:32',
                'checkpassword'     => 'require|confirm:password',
                'captcha'           => 'require',
            ]);
            $validate->message([
                'username.require'          => '手机或邮箱不能为空',
                'verification_code.require' => '手机或邮箱验证码不能为空',
                'password.require'          => '密码不能为空',
                'password.max'              => '密码不能超过32个字符',
                'password.min'              => '密码不能小于6个字符',
                'checkpassword.require'     => '确认密码不能为空',
                'checkpassword.confirm'     => '密码不一致',
                'captcha.require'           => '验证码不能为空',
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            if (!cmf_captcha_check($data['captcha'])) {
                $this->error('验证码错误');
            }
            $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
            if (!empty($errMsg)) {
                $this->error($errMsg);
            }

            $userModel = new UserModel();
            if ($validate::is($data['username'], 'email')) {

                $log = $userModel->emailPasswordReset($data['username'], $data['password']);

            } else if (preg_match('/(^(13\d|14[57]|15[^4\D]|17[13678]|18\d)\d{8}|170[^346\D]\d{7})$/', $data['username'])) {
                $user['mobile'] = $data['username'];
                $log            = $userModel->mobilePasswordReset($data['username'], $data['password']);
            } else {
                $log = 2;
            }
            switch ($log) {
                case 0:
                    $this->success('密码重置成功', $this->request->root());
                    break;
                case 1:
                    $this->error("您的账户尚未注册");
                    break;
                case 2:
                    $this->error("您输入的账号格式错误");
                    break;
                default :
                    $this->error('未受理的请求');
            }

        } else {
            $this->error("请求错误");
        }
    }


}